/**
 * Created: 04/06/2010
 */
package org.klarblick.linkbox.web.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.klarblick.linkbox.model.dao.ILinkDao;
import org.klarblick.linkbox.model.entities.Link;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * Controller that handles requests to the link management page.
 * 
 * @author Sebastian Engel <sebastian.engel@klarblick.org>
 *
 */
@Controller
@RequestMapping("/link-management")
public class LinkManagementController {

	private static Log log = LogFactory.getLog(LinkManagementController.class);
	
	@Autowired
	private ILinkDao linkDao;

	/**
	 * Renders the link management page.
	 * 
	 * @return the ModelAndView
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView handleRenderRequest() {
		log.trace("Rendering LinkManagement");

		ModelAndView modelAndView = new ModelAndView("link-management");
		modelAndView.addObject("existingLinks", linkDao.findAll());
		modelAndView.addObject("link", new Link());
		return modelAndView;
	}

	/**
	 * Handles the form submission for adding a new link.
	 * 
	 * @param link The link to add
	 * @return the target redirect string
	 */
	@RequestMapping(method = RequestMethod.POST)
	public String handleAddLinkAction(@ModelAttribute("link") Link link) {
		log.debug("Adding link: " + link.getName());
		linkDao.addLink(link);
		return "redirect:/link-management";
	}
}
